import { defineStore } from 'pinia'
import { ref } from 'vue'
import { register, login, getLoginUser } from '@/api/user.js'
import { showNotify } from 'vant'
import router from '@/router/index.js'

export const useUserStore = defineStore('user', () => {
  // 用户信息状态
  const userInfo = ref(null)

  // 登录与否
  const isLogged = ref(false)

  // 注册操作
  const onRegister = async (formData) => {
    const res = await register(formData)
    if (res.code === 0) {
      const id = res.data
      const response = await getLoginUser({ id: id })
      if (response?.code === 0) {
        userInfo.value = response.data
        isLogged.value = true
        showNotify({ type: 'success', message: '注册成功...' })
        router.push('/index') // 注册成功后跳转
      } else {
        showNotify({ type: 'danger', message: response?.message })
      }
    } else {
      showNotify({ type: 'danger', message: res?.message })
    }
  }

  // 登录操作
  const onLogin = async (formData) => {
    const res = await login(formData)
    if (res.code === 0) {
      userInfo.value = res.data
      if (userInfo.value.userRole === 'ban') {
        showNotify({ type: 'danger', message: '当前账号已被封禁!' })
        return
      }
      isLogged.value = true
      showNotify({ type: 'success', message: '登录成功...' })
      router.push('/index') // 注册成功后跳转
    } else {
      showNotify({ type: 'danger', message: res?.message })
    }
  }

  // 退出登录
  const onLogout = () => {
    isLogged.value = false
    userInfo.value = null
  }

  // 设置账号信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  return { userInfo, isLogged, onLogin, onRegister, onLogout, setUserInfo }
}, {
  persist: {
    key: 'user_data', // 持久化存储的key
    storage: localStorage // 指定存储方式
  }
})
